package com.aaa.config;

import com.aaa.util.DefaultMsg;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class MyConfig01 extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
@Bean
public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
}

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().mvcMatchers("/stu/**").permitAll().
        anyRequest().authenticated().and().formLogin().loginPage("/listByZm").permitAll().
        loginProcessingUrl("/listByZm").defaultSuccessUrl("/test1").successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                DefaultMsg defaultMsg=new DefaultMsg();
                Object user = authentication.getPrincipal();
                defaultMsg.setTarget(user);
                response.setContentType("application/json;charset=UTF-8");
                //吧defaultMsg转成json字符串
                String json=new Gson().toJson(defaultMsg);
                PrintWriter writer=response.getWriter();
                writer.print(json);
                writer.close();
            }
        }).failureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                DefaultMsg defaultMsg=new DefaultMsg();
                defaultMsg.setSuccess(0);
                defaultMsg.setError("用户或密码错误");
                response.setContentType("application/json;charset=UTF-8");
                //吧defaultMsg转成json字符串
                String json=new Gson().toJson(defaultMsg);
                PrintWriter writer=response.getWriter();
                writer.print(json);
                writer.close();
            }
        }).and().
        logout().logoutUrl("/logOut").logoutSuccessUrl("/logOutSuccess").permitAll();

        http.csrf().disable();
        //禁用spring security的iframe保护策略
        http.headers().frameOptions().disable();
        http.cors();
        http.exceptionHandling().
        accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
//                httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/noPermit.jsp")
//                        .forward(httpServletRequest,response);
            }
        });
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().mvcMatchers("/scripts/**");
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encode=bCryptPasswordEncoder.encode("654321");
        boolean matches = bCryptPasswordEncoder.matches("654321", "$2a$10$P/pzsVCcev4hVwWKvquMjO1P2JMXZtmGk32E5WawPydwgu3HiQIe.");
        System.out.println(matches);
        System.out.println(encode);
    }
}
